import { getPSAppDEUILogicByModelObject, IPSAppDEUIAction } from '@ibiz/dynamic-model-api';
import { IUIDataParam, IUIEnvironmentParam, IUIUtilParam } from '../../interface';
import { LogUtil } from '../../util';
import { AppUILogicService } from '../../logic';

export class AppDEUIAction {
  /**
   * 模型数据
   *
   * @memberof AppDEUIAction
   */
  protected actionModel!: IPSAppDEUIAction;

  /**
   * 初始化AppDEUIAction
   *
   * @memberof AppDEUIAction
   */
  constructor(opts: any, context?: any) {
    this.actionModel = opts;
  }

  /**
   * 执行界面逻辑
   *
   * @param UIDataParam 操作数据参数
   * @param UIEnvironmentParam 操作环境参数
   * @param UIUtilParam 操作工具参数
   *
   * @memberof AppDEUIAction
   */
  public async executeDEUILogic(
    UIDataParam: IUIDataParam,
    UIEnvironmentParam: IUIEnvironmentParam,
    UIUtilParam: IUIUtilParam,
  ) {
    if (Object.is(this.actionModel.uILogicType, 'DEUILOGIC')) {
      const appDEUILogic = await getPSAppDEUILogicByModelObject(this.actionModel);
      if (appDEUILogic) {
        return await AppUILogicService.getInstance().onExecute(
          appDEUILogic,
          UIDataParam,
          UIEnvironmentParam,
          UIUtilParam,
        );
      } else {
        LogUtil.warn('未找到实体界面处理逻辑对象');
      }
    } else {
      LogUtil.warn('未实现应用界面处理逻辑');
    }
  }

  /**
   * 执行界面行为之前（准备参数）
   *
   * @param UIDataParam 操作数据参数
   * @param UIEnvironmentParam 操作环境参数
   * @param UIUtilParam 操作工具参数
   *
   * @memberof AppDEUIAction
   */
  public beforeExecute(UIDataParam: IUIDataParam, UIEnvironmentParam: IUIEnvironmentParam, UIUtilParam: IUIUtilParam) {
    let args: any[] = [];
    if (UIDataParam.data) {
      if (Array.isArray(UIDataParam.data)) {
        args = UIDataParam.data;
      } else {
        args = [UIDataParam.data];
      }
    }
    const { sender: actionContext, event: event } = UIDataParam;
    const { ctrl: xData } = UIEnvironmentParam;
    return { args: args, actionContext: actionContext, event: event, xData: xData };
  }
}
